package com.example.service;

import cn.hutool.json.JSONObject;
import com.example.common.Result;
import com.example.entity.TrainingLog;
import com.example.mapper.TrainingLogsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class TrainingLogsService {

    @Resource
    private TrainingLogsMapper trainingLogsMapper;

    public Result upTraining(TrainingLog trainingLog) {
        // 获取当前日期的年月日部分
        LocalDate today = LocalDate.now();
        // 将LocalDate转换为Date对象（时间部分为00:00:00）
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
        trainingLog.setLogDate(date);
        TrainingLog old = trainingLogsMapper.getByUserIdDateTrainId(trainingLog);
        if(old != null){
            if(!trainingLogsMapper.up(trainingLog)){
                return Result.error("打卡失败");
            }
            return Result.success("打卡成功");
        }
        if(!trainingLogsMapper.add(trainingLog)){
            return Result.error("打卡失败");
        }
        return Result.success("打卡成功");
    }

    public Result list(TrainingLog trainingLog) {
        List<JSONObject> result = trainingLogsMapper.list(trainingLog);
        return Result.success(result);
    }

    public Result listAll() {
        List<TrainingLog> trainingLogList = trainingLogsMapper.listAll();
        return Result.success(trainingLogList);
    }

    public Result listToday(TrainingLog trainingLog) {
        // 获取当前日期的年月日部分
        LocalDate today = LocalDate.now();
        // 将LocalDate转换为Date对象（时间部分为00:00:00）
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
        trainingLog.setLogDate(date);
        List<JSONObject> result = trainingLogsMapper.listToday(trainingLog);
        return Result.success(result);
    }
}
